//
//  CUserPageCtrl.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-19.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CSearchPageCtrl.h"

@implementation CSearchPageCtrl

static CSearchPageCtrl *g_Instance = nil;

//topbar
@synthesize m_TopBar;

@synthesize m_SearchView;
@synthesize m_ConditonView;
@synthesize m_Value;
@synthesize m_Cancel;
@synthesize m_BgView;

+(id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (!g_Instance)
        {
            g_Instance = [super allocWithZone:zone];
        }
    }
    
    return g_Instance;
}

+(CSearchPageCtrl*)DefaultSearchPage
{
    if (!g_Instance)
    {
        g_Instance = [[CSearchPageCtrl alloc] init];
    }
    
    return g_Instance;
}

+(void)DestroySearchPage
{
    if (g_Instance)
    {
        [g_Instance release];
    }
    
    g_Instance = nil;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib. 
    self.view.backgroundColor = [UIColor clearColor];
    self.m_Value = [NSString stringWithString:@","];
    
    m_BgView = [[UIView alloc] initWithFrame:CGRectMake(0, TOPBAR_HEIGHT, self.view.frame.size.width, self.view.frame.size.height-TOPBAR_HEIGHT)];
    m_BgView.backgroundColor = [UIColor blackColor];
    m_BgView.alpha = 0.6;
    [self.view addSubview:m_BgView];
    [m_BgView release];
    
    /*UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, TAB_HEIGHT)];
    view.image = [UIImage imageNamed:@"barbg.png"];
    [self.view addSubview:view];
    [view release];*/
    
    m_TopBar = [[CTopBarView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, TOPBAR_HEIGHT)];
    [self.view addSubview:m_TopBar];
    [m_TopBar release];
    
    m_SearchView = [[CSearchView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-50, TOPBAR_HEIGHT)];
    m_SearchView.backgroundColor = self.view.backgroundColor;
    m_SearchView.delegate = self;
    [self.view addSubview:m_SearchView];
    [m_SearchView release];
    
    m_Cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [m_Cancel setBackgroundImage:[UIImage imageNamed:@"cancel.png"] forState:UIControlStateNormal];
    //[m_Cancel setTitle:@"取消" forState:UIControlStateNormal];
    m_Cancel.frame = CGRectMake(self.view.frame.size.width-40, 3, 30, 30);
    [m_Cancel addTarget:self action:@selector(OnCancelBtnDown:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:m_Cancel];
    
    /*NSArray *items = [NSArray arrayWithObjects:@"好友昵称", @"美食名称", @"城市", @"餐馆", @"描述", @"地址", nil];
    m_ConditonView = [[CSearchConditionView alloc] initWithFrame:CGRectMake(20, 36, 210, 30) Items:items];
    [self.view addSubview:m_ConditonView];
    [m_ConditonView release];
    
    [m_SearchView AddSearchConditionView:m_ConditonView];*/
}

-(void)dealloc
{
    [super dealloc];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//topbar
-(void)DidTopBarBtnsClicked:(UIButton *)btn
{
    [self OnTopBarDown:btn];
}

-(void)OnCancelBtnDown:(UIButton*)sender
{
    m_SearchView.m_SearchBar.text = nil;
    [self CommitSearchRequest:@"cancel"];
}

-(void)OnTopBarDown:(UIButton*)sender
{
    //return
    if (0 == sender.tag)
    {
        //
    }
    //option
    else if (1 == sender.tag)
    {
        [self HiddenSearchPageCtrl];
        [[CUserPageCtrl DefaultUserPage] ShowOptionPageCtrl];
    }
    //home
    else if (2 == sender.tag)
    {
        [self HiddenSearchPageCtrl];
        [[CMainPageCtrl DefaultMainPageCtrl] ShowHomePageCtrl];
    }
    else {;}
}

//self
-(void)ShowSearchPageCtrl
{
    if (0.0 == self.view.alpha)
    {
        [m_SearchView.m_SearchBar becomeFirstResponder];
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        //[UIView setAnimationDelegate:self];
        //[UIView setAnimationDidStopSelector:@selector(DidSearchViewShown)];
        self.view.alpha = 1.0;
        //m_SearchView.center = CGPointMake(m_SearchView.center.x, m_SearchView.center.y+ m_SearchView.frame.size.height);
        [UIView commitAnimations];
    }
}

-(void)DidSearchViewShown
{
    //
}

-(void)HiddenSearchPageCtrl
{
    if (1.0 == self.view.alpha)
    {
        [m_SearchView.m_SearchBar resignFirstResponder];
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        //[UIView setAnimationDelegate:self];
        //[UIView setAnimationDidStopSelector:@selector(DidSearchViewHidden)];
        self.view.alpha = 0.0;
        //m_SearchView.center = CGPointMake(m_SearchView.center.x, m_SearchView.center.y- m_SearchView.frame.size.height);
        [UIView commitAnimations];
    }
}

-(void)DidSearchViewHidden
{
    //
}

//searchbar
-(void)DidSearchViewSelected:(int)index Text:(NSString *)text
{
    NSString *value = nil;
    
    switch (index)
    {
        case 0:
            value = @"nicename";
            break;
        case 1:
            value = @"picname";
            break;
        case 2:
            value = @"city";
            break;
        case 3:
            value = @"restaurant";
            break;
        case 4:
            value = @"caption";
            break;
        case 5:
            value = @"addr";
            break;
        case -1:
            value = @"cancel";
            break;
        default:
            break;
    }

    //self.m_Param = [NSString stringWithString:value];
    
    [self CommitSearchRequest:value];
}

-(void)CommitSearchRequest:(NSString*)value
{
    [self HiddenSearchPageCtrl];
    
    if ([value isEqualToString:@"cancel"])
    {
        
        self.m_Value = nil;
        [[CMainPageCtrl DefaultMainPageCtrl] TabSearchAction:0];
    }
    else
    {
        //1重置搜索条件否则2
        int state = 1;
        if ([m_Value isEqualToString:m_SearchView.m_SearchBar.text])
            state = 2;
        else 
            self.m_Value = m_SearchView.m_SearchBar.text;
        
        [[CMainPageCtrl DefaultMainPageCtrl] TabSearchAction:state];
    }
}

//table
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCellStyle style = UITableViewCellStyleValue1;
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseCell"];
	
	if (nil == cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"BaseCell"] autorelease];
    }
    
    return cell;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (0 == [m_SearchView.m_SearchBar.text length])
    {
        self.m_Value = nil;
        [self CommitSearchRequest:@"cancel"];
    }
    else 
    {
        [self HiddenSearchPageCtrl];
    }
}

-(void)DidReceiveSearchRets:(NSDictionary*)data Flag:(id)flag
{
    int nCode = [[data objectForKey:@"Msg_error"] intValue];
    
    NSLog(@"========>搜索结果:%@", data);
    
    if (0 == nCode)
    {
        [[CMainPageCtrl DefaultMainPageCtrl] InitMainPageView:YES];
        [CMainPageCtrl DefaultMainPageCtrl].m_Command = GSearchP;
        [[CMainPageCtrl DefaultMainPageCtrl].m_TabView.m_Tab AddTabItem:@"搜索"];
        [[CMainPageCtrl DefaultMainPageCtrl].m_TabView.m_Tab SetFocus:3];
        [[CMainPageCtrl DefaultMainPageCtrl] DidReceiveProductsFromSvr:data Info:[NSNumber numberWithInt:GSearchP]];
    }
    else if (18 == nCode)
    {
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"未找到结果" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [alter show];
        [alter autorelease];
    }
    else 
    {
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"搜索请求被远程服务器拒绝" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [alter show];
        [alter autorelease];
    }
}

-(void)DidOperationFinished:(COperation *)op Data:(NSData *)data Other:(id)other UserInfo:(id)userinfo
{
    NSString    *json = nil;
    NSDictionary *dic = nil;
    
    if (data)
    {
        NSLog(@"<====results of search====>");
        
        json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        dic  = [json JSONValue];
        NSLog(@"\r\n\r\n收到的搜索结果原始数据:%@\r\n\r\n",json);
        
        if (dic)
        {
            [self DidReceiveSearchRets:dic Flag:other];
        }
        else 
        {
            [self DidReceiveSearchRets:[NSDictionary dictionaryWithObjectsAndKeys:@"-100", @"Msg_error", nil] Flag:nil];
        }
        
        [json release];
    }
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)DidOperationError:(COperation *)op Error:(NSError *)error Other:(id)other UserInfo:(id)userinfo
{
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)DidOperationTimeOut:(COperation *)op Other:(id)other UserInfo:(id)userinfo
{
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

@end
